<template>
  <div style="width:100%">
    <div id="editor" style="width:100%">
      <slot />
    </div>
    <el-dialog :visible.sync="routerConfigShow" title="配置路由" width="500px" :close-on-click-modal="false">
      <el-input v-model="routerTitle" placeholder="路由文字" class="router_input" v-tab="{index: 1, max: 2, area: 'editor'}"></el-input>
      <el-input v-model="routerUrl" placeholder="如https://..." class="router_input" v-tab="{index: 2, max: 2, area: 'editor'}"></el-input>
      <el-button @click="addRouterLink" type="primary" class="router_btn" round>
        确定
      </el-button>
    </el-dialog>
  </div>
</template>

<script>
import E from 'wangeditor';
import { getTmpCache } from '@u/cache.js';

let that = null;

export default {
  name: 'Editor',
  props: {
    placeholder: {
      type: String,
      default: ''
    },
    content: {
      type: String,
      default: ''
    },
    height: {
      type: [String, Number],
      default: 400
    }
  },
  watch: {
    content: {
      handler(newVal) {
        if (!this.editor) {
          this.createEditor();
        }
        if (newVal && !this.initContent) {
          this.initContent = newVal;
          this.$nextTick(() => {
            this.editor.txt.html(newVal); // 重新设置编辑器内容
          });
        }
      },
      deep: true,
      immediate: true
    }
  },
  data() {
    return {
      editor: null,
      initContent: '',
      routerConfigShow: false,
      routerTitle: '',
      routerUrl: ''
    };
  },
  created() {
    that = this;
  },
  methods: {
    addRouterLink() {
      if (!this.routerTitle) {
        return;
      }
      if (!this.routerUrl) {
        return;
      }
      this.editor.cmd.do('insertHTML', `<a href="${ this.routerUrl }">${ this.routerTitle }</a>`);
      this.routerConfigShow = false;
    },
    createEditor() {
      const { BtnMenu } = E; // 注册一个菜单
      class RouterLinkMenu extends BtnMenu {
        constructor(editor) {
          const $elem = E.$(
            `<div class="w-e-menu router_link">
              <div class="tooltip">路由</div>
              <span>L</span>
            </div>`
          );
          super($elem, editor);
        }
        clickHandler() { // 菜单点击事件
          that.routerConfigShow = true;
        }
        tryChangeActive() { // 菜单是否被激活
          // this.active();
          // this.unActive();
        }
      }
      this.$nextTick(() => {
        this.editor = new E('#editor');
        const menuKey = 'routerLink'; // 菜单 key ，各个菜单不能重复
        this.editor.menus.extend(menuKey, RouterLinkMenu);
        this.editor.config.menus = this.editor.config.menus.concat(menuKey);
        this.editor.config.menus = [ // 默认情况下，显示所有菜单
          'head',
          'bold',
          'fontSize',
          'fontName',
          'italic',
          'underline',
          'strikeThrough',
          'indent',
          'lineHeight',
          'foreColor',
          'backColor',
          'list',
          'justify',
          'link',
          'routerLink',
          'quote',
          // 'emoticon',
          'image',
          // 'video',
          'table',
          // 'code',
          'splitLine',
          'undo',
          'redo'
        ];
        this.editor.config.customAlert = (s, t) => {
          switch (t) {
            case 'success':
              this.$message.success(s);
              break;
            case 'info':
              this.$message.info(s);
              break;
            case 'warning':
              this.$message.warning(s);
              break;
            case 'error':
              this.$message.error(s);
              break;
            default:
              this.$message.info(s);
              break;
          }
        };
        // this.editor.config.focus = false; // 取消自动 focus
        this.editor.config.placeholder = this.placeholder; // 可以修改 placeholder 的提示文字
        this.editor.config.zIndex = 10; // 编辑器 z-index 默认为 10000
        this.editor.config.height = this.height;
        this.editor.config.uploadImgServer = '/api/userSystem/Common/Files'; // 配置 server 接口地址
        this.editor.config.uploadImgMaxSize = 2 * 1024 * 1024; // 限制图片大小
        this.editor.config.uploadImgAccept = ['jpg', 'jpeg', 'png', 'gif']; // 限制图片类型
        this.editor.config.uploadImgMaxLength = 1; // 限制一次最多能传几张图片
        this.editor.config.withCredentials = true; // 跨域上传中如果需要传递 cookie 需设置 withCredentials
        this.editor.config.uploadImgHeaders = { // 上传图片时添加 http 请求的 header
          Authorization: getTmpCache('token'),
        };
        this.editor.config.onchange = newHtml => { // 配置 onchange 回调函数
          this.$emit('change', newHtml);
        };
        this.editor.config.onfocus = newHtml => { // 配置 onfocus 回调函数
          this.$emit('focus', newHtml);
        };
        this.editor.config.onblur = newHtml => { // 配置 onblur 回调函数
          this.$emit('blur', newHtml);
        };
        this.editor.config.uploadImgHooks = {
          customInsert: (insertImgFn, res) => { // 图片上传并返回了结果，想要自己把图片插入到编辑器中
            // insertImgFn 可把图片插入到编辑器，传入图片 src ，执行函数即可
            if (res.code == 200) {
              insertImgFn(res.data.url);
            }
          }
        };
        this.editor.create();
      });
    }
  }
};
</script>

<style lang="scss" scoped>
::v-deep {
  .w-e-menu.router_link {
    position: relative;
    .tooltip {
      display: none;
      color: #ffffff;
      background: #404040;
      padding: 5px;
      border-radius: 4px;
      position: absolute;
      bottom: 100%;
      margin-bottom: 14px;
      &::after {
        content: '';
        display: block;
        border: 5px solid transparent;
        border-top-color: #404040;
        position: absolute;
        top: 100%;
        left: 50%;
        transform: translateX(-50%);
      }
    }
    > span {
      font-size: 17px;
      font-weight: 600;
      color: #999;
    }
    &:hover {
      .tooltip {
        display: block;
      }
      > span {
        color: #333;
      }
    }
  }
}
.router_input {
  display: block;
  width: 360px;
  margin: 0 auto 12px;
}
.router_btn {
  display: block;
  margin: 20px auto 0;
}
</style>
